package com.smmisia.article.asept;

import com.alibaba.fastjson2.JSON;
import com.smmisia.article.aop.PreventDuplicateSubmit;
import com.smmisia.article.utils.DistributedLockHelper;
import com.smmisia.common.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class PreventDuplicateSubmitAspect {

    @Autowired
    private DistributedLockHelper lockHelper;

    @Around("@annotation(preventDuplicateSubmit)")
    public Object doAround(ProceedingJoinPoint pjp, PreventDuplicateSubmit preventDuplicateSubmit) throws Throwable {
        // 获取请求参数的唯一标识
        String params = JSON.toJSONString(pjp.getArgs());
        String requestId = DigestUtils.md5Hex(params);
        String lockKey = preventDuplicateSubmit.prefix() + requestId;

        boolean locked = false;
        try {
            // 尝试获取锁
            locked = lockHelper.tryLock(lockKey,
                    preventDuplicateSubmit.waitTime(),
                    preventDuplicateSubmit.leaseTime());
            if (!locked) {
                return Result.fail("请勿重复提交");
            }

            // 执行业务逻辑
            return pjp.proceed();

        } finally {
            if (locked) {
                lockHelper.unlock(lockKey);
            }
        }
    }
}
